package grape.workflow.rest.flowable.ui.admin;

import org.flowable.ui.admin.dto.ServerConfigRepresentation;
import org.flowable.ui.admin.service.engine.ServerConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.List;

/**
 * Created by yangwei
 * Created at 2020/6/8 13:50
 */
public class MinimalDataGenerator  implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(MinimalDataGenerator.class);

    @Autowired
    protected ServerConfigService serverConfigService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 发现在实现运行时event.getApplicationContext().getParent()始终不为null，导致初始不了数据，这里加一个上上级
        if (event.getApplicationContext().getParent() == null || event.getApplicationContext().getParent().getParent() == null) { // Using Spring MVC, there are multiple child contexts. We only care about the root
            LOGGER.info("Verifying if minimal data is present");

            List<ServerConfigRepresentation> serverConfigs = serverConfigService.findAll();
            if (serverConfigs.size() == 0) {
                LOGGER.info("No server configurations found, creating default server configurations");
                serverConfigService.createDefaultServerConfigs();

            } else if (serverConfigs.size() == 4) {
                serverConfigService.createCmmnDefaultServerConfig();

            } else if (serverConfigs.size() == 5) {
                serverConfigService.createAppDefaultServerConfig();
            }
        }
    }
}
